// ============================================
// internal/console/vnc_viewer.go - noVNC Web 查看器
// ============================================

package console

import (
	"embed"
	"fmt"
	"html/template"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

//go:embed templates/*
var templates embed.FS

// VNCWebViewer Web VNC 查看器
type VNCWebViewer struct {
	logger *logrus.Logger
}

func NewVNCWebViewer(logger *logrus.Logger) *VNCWebViewer {
	return &VNCWebViewer{
		logger: logger,
	}
}

// ServeVNCViewer 提供 VNC Web 查看器
func (v *VNCWebViewer) ServeVNCViewer(c *gin.Context) {
	connID := c.Param("connection_id")
	vmName := c.Param("vm_name")
	token := c.Query("token")

	// 构建 WebSocket URL
	wsURL := fmt.Sprintf("ws://%s/api/v1/console/vnc/%s/%s?token=%s",
		c.Request.Host, connID, vmName, token)

	// 渲染 HTML 模板
	tmpl, err := template.ParseFS(templates, "templates/vnc_viewer.html")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	data := map[string]interface{}{
		"VMName":  vmName,
		"WSURL":   wsURL,
		"Version": "1.0.0",
		"Year":    time.Now().Year(),
	}

	c.Header("Content-Type", "text/html; charset=utf-8")
	if err := tmpl.Execute(c.Writer, data); err != nil {
		v.logger.WithError(err).Error("Failed to render template")
	}
}
